import Axios from 'axios' // 此处引入axios官方文件
import { baseURL } from 'boot/env'
import { i18n } from 'boot/i18n'
import { LoadingBar } from 'quasar'
import { userStores } from 'src/stores/user-stores'
import { getStore } from 'src/utils/storage'
import { isInIframe } from 'src/utils/utils.js'
import { addPending } from './cancelRepeatRquest'
import { getReturn, refreshToken, responseHandle, serialize } from './utils'

const axios = Axios.create({
  baseURL, timeout: 50000,
  validateStatus: status => status >= 200 && status <= 500 // 区间外的状态码走error
})

// 添加请求拦截器
axios.interceptors.request.use(config => {
  const token = getStore('Token', 'L') || ''
  config.headers = {
    lang: i18n.locale.value, Authorization: token, 'Content-Type': 'application/json;charset=UTF-8'
  }
  let nonLoadingBar = false
  if (['post', 'put'].includes(config.method.toLocaleLowerCase()) && config.headers.serialize) {
    config.data = serialize(config.data) // 参数统一处理
  } else if (['get'].includes(config.method.toLocaleLowerCase())) {
    config.params = config.params || config.data // 参数统一处理
  }
  if (config.data?.nonLoadingBar) {
    nonLoadingBar = config.data.nonLoadingBar
    delete config.data.nonLoadingBar
  }
  if (config.params?.nonLoadingBar) {
    nonLoadingBar = config.params.nonLoadingBar
    delete config.params.nonLoadingBar
  }
  !isInIframe() && !nonLoadingBar && !LoadingBar.isActive && LoadingBar.start()
  addPending(config)
  return config
}, error => Promise.reject(error))

// 添加响应拦截器
axios.interceptors.response.use(res => {
  LoadingBar.stop()
  if (res.status === 201) userStores().SET_TOKEN(res.headers.authorization)
  return refreshToken(res, axios)
}, error => {
  LoadingBar.stop()
  if (Axios.isCancel(error)) return Promise.reject(error)
  if (error.message) {
    const tempCode = error.message.split(' status code ')[1]
    return responseHandle(tempCode, error)
  }
  getReturn(i18n.t('UnknownError')).then()
  return Promise.reject(error)
})

export default axios